package com.shy.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.shy.config.model.SecurityUser;
import com.shy.entity.Permission;
import com.shy.entity.User;
import com.shy.mapper.PermissionMapper;
import com.shy.mapper.RoleMapper;
import com.shy.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private PermissionMapper permissionMapper;
    @Resource
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户
        User user = userMapper.selectByUsername(username);
        // 判断用户是否存在
        if (ObjUtil.isEmpty(user)) {
            throw new InternalAuthenticationServiceException("用户名或密码错误");
        }
        //根据用户标识权限查询操作
        Set<String> permissions =permissionMapper.selectPermissionByUserId(user.getId());
        //根据用户标识权限查询菜单操作
        Set<Permission> menus = permissionMapper.selectMenuByUserPermissionId(user.getId());
        // 根据用户标识查询用户角色
        Set<String> roles = roleMapper.selectRoleByUserId(user.getId());
        //创建安全用户对象
        SecurityUser securityUser = SecurityUser.builder()
                .id(user.getId())
                .loginAct(user.getLoginAct())
                .loginPwd(user.getLoginPwd())
                .name(user.getName())
                .phone(user.getPhone())
                .email(user.getEmail())
                .accountNoExpired(user.getAccountNoExpired())
                .credentialsNoExpired(user.getCredentialsNoExpired())
                .accountNoLocked(user.getAccountNoLocked())
                .accountEnabled(user.getAccountEnabled())
                .createTime(user.getCreateTime())
                .createBy(user.getCreateBy())
                .lastLoginTime(user.getLastLoginTime())
                .perms(permissions)
                .roles(roles)
                .menus(menus)
                .build();
        return securityUser;
    }
}
